package com.guit.hrms.controller;

import com.guit.hrms.dto.approval.ApprovalOfferDTO;
import com.guit.hrms.dto.approval.ApprovalPlanDTO;
import com.guit.hrms.po.utilsPO.PageBean;
import com.guit.hrms.po.utilsPO.Result;
import com.guit.hrms.po.Transaction;
import com.guit.hrms.service.ApprovalService;
import com.guit.hrms.utils.ThreadLocalUtil;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.Objects;


@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/api/approval")
public class ApprovalController {
    @Autowired
    private ApprovalService approvalService;

    /**
     * 获取请假记录
     * @param page 当前页
     * @param pageSize 当前页面展示的数据条数
     * @param deptId 部门id
     * @param type 请假类型
     * @param approvalStatus 审批状态
     * @param revokeStatus 销假状态
     * @return 请假记录
     */
    @GetMapping
    public Result queryLeaveRecords(@RequestParam(defaultValue = "1") Integer page ,
                                    @RequestParam(defaultValue = "10") Integer pageSize,
                                    Integer deptId, Integer type,
                                    Integer approvalStatus, Integer revokeStatus,
                                    Integer extensionStatus){
        PageBean leaveRecords = approvalService.queryLeaveRecords(page,pageSize,deptId,type,approvalStatus,revokeStatus,extensionStatus);
        return Result.success(leaveRecords);
    }

    /**
     * 审批请假
     * @param transaction 审批信息
     * @return 审批结果
     */
    @PatchMapping
    public Result approvingLeave(@RequestBody Transaction transaction){
        if (transaction.getId() == null && (transaction.getApprovalStatus() == null || transaction.getRevokeStatus() == null || transaction.getExtensionStatus() == null)){
            return Result.error("请选择要审批的请假记录以及要修改的状态");
        } else {
            Integer result = approvalService.approvingLeave(transaction);
            if (result == 0){
                return Result.error("审批失败");
            } else {
                return Result.success("审批成功");
            }
        }
    }

//    /**
//     * 获取销假记录
//     * @param page 当前页
//     * @param pageSize 当前页面展示的数据条数
//     * @param deptId 部门id
//     * @param type 请假类型
//     * @param revokeStatus 销假状态
//     * @return 销假记录
//     */
//    @GetMapping("/cancel")
//    public Result queryCancelRecords(@RequestParam(defaultValue = "1") Integer page ,
//                                    @RequestParam(defaultValue = "10") Integer pageSize,
//                                    Integer deptId, Integer type, Integer revokeStatus){
//        PageBean cancelRecords = approvalService.queryCancelRecords(page,pageSize,deptId,type,revokeStatus);
//        return Result.success(cancelRecords);
//    }
//
//    /**
//     * 审批销假
//     * @param transaction 审批信息
//     * @return 结果
//     */
//    @PatchMapping("/cancel")
//    public Result approvingCancel(@RequestBody Transaction transaction){
//        if (transaction.getId() == null || transaction.getRevokeStatus() == null){
//            return Result.error("请选择要审批的销假记录以及要修改的销假状态");
//        } else {
//            Integer result = approvalService.approvingCancel(transaction);
//            if (result == 0){
//                return Result.error("审批销假失败");
//            } else {
//                return Result.success("审批销假成功");
//            }
//        }
//    }

    /**
     * 获取招聘计划(分页)
     * @param page 当前页
     * @param pageSize 页面记录大小
     * @param planType 招聘计划类型
     * @return 招聘计划列表
     */
    @GetMapping("/recruit/announcements/get")
    public Result getRecruitmentPlan(@RequestParam(defaultValue = "1") Integer page ,
                                     @RequestParam(defaultValue = "10") Integer pageSize,
                                     Integer planType){

        PageBean pageBean = approvalService.getRecruitmentPlan(page,pageSize,planType);
        return Result.success(pageBean);
    }

    /**
     * 审批招聘计划（修改招聘计划的审批状态）
     * @param approvalPlanDTO 审批信息
     * @return 结果
     */
    @PatchMapping("/recruit/announcements")
    public Result updateRecruitmentPlan(@Validated @RequestBody ApprovalPlanDTO approvalPlanDTO){
        Map<String,Object> map = ThreadLocalUtil.get();
        String employeeId = (String) map.get("employeeId");
        System.out.println("employeeId = " + employeeId);


        Integer result = approvalService.updateRecruitmentPlan(approvalPlanDTO,employeeId);
        if (result == 1){
            return Result.success();
        } else {
            return Result.error();
        }
    }

    /**
     * 获取发offer申请(分页)
     * @param page 当前页
     * @param pageSize 页面记录大小
     * @param status 审批状态
     * @return 招聘计划列表
     */
    @GetMapping("/offer")
    public Result getApplyOfferMsg(@RequestParam(defaultValue = "1") Integer page ,
                                     @RequestParam(defaultValue = "10") Integer pageSize,
                                     Integer status){

        PageBean pageBean = approvalService.getApplyOfferMsg(page,pageSize,status);
        return Result.success(pageBean);
    }

//    /**
//     * 生成账号
//     * @return 账号信息
//     */
//    @PostMapping("/offer/createAccount")
//    public Result createAccount(){
//        CreateAccountVO createAccountVO = approvalService.createAccount();
//        return createAccountVO != null ? Result.success(createAccountVO) : Result.error("生成失败");
//    }

    /**
     * 审批发offer申请
     * @param id 申请ID
     * @param status 审批状态（1-通过，2-拒绝）
     * @param content 邮件内容
     * @param offerFile offer文件
     * @param onboardingTime 入职时间
     * @param onboardingPlace 入职地点
     * @param expiryTime offer有效期（仅在通过时需要）
     * @return 审批结果
     */
    @PatchMapping("/offer")
    public Result updateApplyOfferMsg(@RequestParam @NotNull(message = "id不能为空") Integer id,
                                      @RequestParam @NotNull(message = "status不能为空") Integer status,
                                      String content,
                                      MultipartFile offerFile,
                                      LocalDateTime onboardingTime,
                                      String onboardingPlace,
                                      LocalDateTime expiryTime){
        try {
            // 状态校验
            if (status != 1 && status != 2) {
                return Result.error("审批状态只能是1(通过)或2(拒绝)");
            }

            // 拒绝时，不需要其他参数
            if (status == 2) {
                ApprovalOfferDTO approvalOfferDTO = new ApprovalOfferDTO(id, status, null, null, null, null, null);
                int result = approvalService.updateApplyOfferMsg(approvalOfferDTO);
                return result == 1 ? Result.success("已拒绝此offer申请") : Result.error("审批操作失败，请确认该申请是否存在且未被处理");
            }

            // 通过时的参数校验
            if (content == null || content.trim().isEmpty()) {
                return Result.error("通过时邮件内容不能为空");
            }
            if (offerFile == null || offerFile.isEmpty()) {
                System.out.println(offerFile+"在这");
                if (offerFile == null) {
                    return Result.error("通过时必须上传offer文件");
                }
                return Result.error("offer文件内容不能为空");
            }
            if (!Objects.equals(offerFile.getContentType(), "application/pdf")) {
                return Result.error("offer文件必须是PDF格式");
            }
            if (onboardingTime == null) {
                return Result.error("通过时必须指定入职时间");
            }
            if (onboardingPlace == null || onboardingPlace.trim().isEmpty()) {
                return Result.error("通过时必须指定入职地点");
            }
            if (expiryTime == null) {
                return Result.error("通过时必须指定offer有效期");
            }

            ApprovalOfferDTO approvalOfferDTO = new ApprovalOfferDTO(id, status, content, offerFile, onboardingTime, onboardingPlace, expiryTime);
            int result = approvalService.updateApplyOfferMsg(approvalOfferDTO);
            if (result == 1) {
                return Result.success("已通过此offer申请");
            } else {
                return Result.error("审批操作失败，请确认该申请是否存在且未被处理");
            }
        } catch (org.springframework.dao.DuplicateKeyException e) {
            log.error("审批发offer申请失败，主键冲突，申请ID：{}，错误信息：{}", id, e.getMessage());
            return Result.error("该offer申请已完成审批，请勿重复操作");
        } catch (org.springframework.dao.DataIntegrityViolationException e) {
            log.error("审批发offer申请失败，数据完整性违规，申请ID：{}，错误信息：{}", id, e.getMessage());
            return Result.error("数据异常，请检查填写的信息是否符合要求");
        } catch (Exception e) {
            log.error("审批发offer申请失败，系统异常，申请ID：{}，错误信息：{}", id, e.getMessage(), e);
            if (e.getMessage() != null){
                return Result.error(e.getMessage());
            }
            return Result.error("系统异常，请联系管理员");
        }
    }
}
